package lovo.practice_7_14.service.impl.UserService;

import lovo.practice_7_14.dao.UserDAO;
import lovo.practice_7_14.dao.impl.UserDAOImpl;
import lovo.practice_7_14.pojo.UserDO;
import lovo.practice_7_14.service.UserService;

import java.sql.SQLException;

public class UserServiceImpl implements UserService {
    private UserDAO userDAO = new UserDAOImpl();

    @Override
    public UserDO getByUsernameAndPwd(String username, String pwd) {
        return userDAO.getByUsernameAndPwd(username, pwd);
    }

    public void saveMoney(String account, double balance) {
        UserDO userDO = userDAO.getById(account);
        userDO.setBalance(userDO.getBalance() + balance);
        userDAO.update(userDO);

    }

    @Override
    public void getMoney(String account, double balance) throws Exception {
        UserDO userDO = userDAO.getById(account);
        if (userDO.getBalance() < balance) {
            throw new Exception("余额不足");
        }
        userDO.setBalance(userDO.getBalance() - balance);
        userDAO.update(userDO);
    }

    @Override
    public double findMoney(String account) {
        UserDO userDO = userDAO.getById(account);
        userDAO.update(userDO);
        return userDO.getBalance();
    }

    @Override
    public void transMoney(String accounter, String accounted, double balance) throws Exception  {

        UserDO userDO = userDAO.getById(accounter);
        UserDO userDO1 = userDAO.getById(accounted);

        if (userDO1 == null) {
            throw new Exception("查无此人");

        }
        if (userDO1.getAccount() == userDO.getAccount()) {
            throw new Exception("不能转给自己");

        }
        if (balance > userDO.getBalance()) {
            throw new Exception("余额不足");

        }

        userDO.setBalance(userDO.getBalance() - balance);
        userDO1.setBalance(userDO1.getBalance() + balance);
        userDAO.update(userDO);
        userDAO.update(userDO1);

    }


}
